//
//  ConditionViewController.m
//  Kjs-iOS
//
//  Created by 江伟 on 16/7/14.
//  Copyright © 2016年 jmhz. All rights reserved.
//

#import "ConditionViewController.h"
#import "MapRadioButton.h"
#import "UIColor+KjsColor.h"
#import "InvestViewController.h"

#define screenW [[UIScreen mainScreen] bounds].size.width //屏幕宽度
#define screenH [[UIScreen mainScreen] bounds].size.height //屏幕高度
#define leftDis 10
#define topDis 10
#define toolViewH 30
#define ItemStatusGroupId @"itemStatus"
#define ItemStatusGroupName @"项目状态"
#define GdItemTypeGroupId @"gdItemType"
#define GdItemTypeGroupName @"项目类型"

@interface ConditionViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic,weak) IBOutlet UIView *itemStatusRGV;
@property (nonatomic,weak) IBOutlet UIView *itemTypeRGV;
@property (nonatomic,weak) IBOutlet UIView *daySelectedV;
@property (nonatomic,weak) IBOutlet UIView *gdAnnualizedBenefitRateV;
@property (nonatomic,weak) IBOutlet UIView *buttonView;
@property (nonatomic,weak) IBOutlet UIButton *confirmBtn;
@property (nonatomic,weak) IBOutlet UIButton *resetBtn;
@property (nonatomic,weak) IBOutlet UIButton *selectedDaysBtn;
@property (nonatomic,weak) IBOutlet UIButton *selectedRateBtn;
@property (nonatomic,weak) IBOutlet UILabel *itemStatus;
@property (nonatomic,weak) IBOutlet UILabel *gdItemType;


@property (nonatomic,strong) NSMutableArray *interestDaysConditons;
@property (nonatomic,strong) UIPickerView *interestDaysPickerV;
@property (nonatomic,strong) UIToolbar *interestDaysPikcerToolBar;
@property (nonatomic,strong) NSString *dayStr;

@property (nonatomic,strong) NSMutableArray *benefitRateConditons;
@property (nonatomic,strong) UIPickerView *benefitRatePickerV;
@property (nonatomic,strong) UIToolbar *benefitRatePikcerToolBar;
@property (nonatomic,strong) NSString *rateStr;

@property (nonatomic,strong) NSMutableArray *itemStatusCond;
@property (nonatomic,strong) NSMutableArray *itemTypeCond;


@property (nonatomic,strong) NSMutableDictionary *statusCondition;
@property (nonatomic,strong) NSMutableDictionary *typeCondition;
@property (nonatomic,strong) NSMutableDictionary *dayLowCondition;
@property (nonatomic,strong) NSMutableDictionary *dayHighCondition;
@property (nonatomic,strong) NSMutableDictionary *rateLowCondition;
@property (nonatomic,strong) NSMutableDictionary *rateHighCondition;
@property (nonatomic,strong) NSMutableArray *rules;

@end

@implementation ConditionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.navigationItem setTitle:@"项目筛选"];
    self.confirmBtn.layer.cornerRadius = 10;
    self.resetBtn.layer.cornerRadius = 10;
    self.selectedDaysBtn.layer.borderColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1].CGColor;
    self.selectedDaysBtn.layer.borderWidth = 1;
    self.selectedRateBtn.layer.borderColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1].CGColor;
    self.selectedRateBtn.layer.borderWidth = 1;
    
    [self.confirmBtn addTarget:self action:@selector(confirmCondition) forControlEvents:UIControlEventTouchUpInside];
    [self.resetBtn addTarget:self action:@selector(resetCondition) forControlEvents:UIControlEventTouchUpInside];
    
    self.itemStatusCond = [[NSMutableArray alloc] initWithArray:[self getConditionStrWithName:ItemStatus]];
    self.itemTypeCond = [[NSMutableArray alloc] initWithArray:[self getConditionStrWithName:GdItemTpye]];

    self.interestDaysConditons = [[NSMutableArray alloc] initWithArray:[self getInterestDaysCondition]];
    self.benefitRateConditons = [[NSMutableArray alloc] initWithArray:[self getBenefitRateCondition]];
    self.dayStr = self.interestDaysConditons[0];
    self.rateStr = self.benefitRateConditons[0];
    
    //设置项目状态和项目类型筛选条件
    self.itemStatusRGV.tag = 1;
    self.itemTypeRGV.tag = 2;
    [self constructeRadioGruopWithCondNum:self.itemStatusCond ColNumber:3 ColSpace:1 RowSpace:1 GroupId:ItemStatusGroupId ContainView:self.itemStatusRGV];
    [self constructeRadioGruopWithCondNum:self.itemTypeCond ColNumber:3 ColSpace:1 RowSpace:1 GroupId:GdItemTypeGroupId ContainView:self.itemTypeRGV];

    //设置项目期限pickerView;
    self.interestDaysPickerV = [[UIPickerView alloc] init];
    self.interestDaysPickerV.dataSource = self;
    self.interestDaysPickerV.delegate = self;
    self.interestDaysPickerV.backgroundColor = [UIColor whiteColor];
    self.interestDaysPickerV.frame = CGRectMake(0, screenH, screenW, 150);
    self.interestDaysPickerV.tag = InterestDays;
    [self.selectedDaysBtn setTitle:self.dayStr forState:UIControlStateNormal];
    [self.selectedDaysBtn  addTarget:self action:@selector(popDaysPickerView) forControlEvents:UIControlEventTouchUpInside];
    
    self.interestDaysPikcerToolBar = [[UIToolbar alloc] init];
    self.interestDaysPikcerToolBar.frame = CGRectMake(0, self.interestDaysPickerV.frame.origin.y, screenW, toolViewH);
    UIBarButtonItem *spacePickerButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *doneInterestDaysPikcerButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(inDayasPickerView)];
    self.interestDaysPikcerToolBar.items = @[spacePickerButton,doneInterestDaysPikcerButton];
    
    [self.view addSubview:self.interestDaysPickerV];
    [self.view addSubview:self.interestDaysPikcerToolBar];
    
    
    //设置年利率pickerView;
    self.benefitRatePickerV = [[UIPickerView alloc] init];
    self.benefitRatePickerV.dataSource = self;
    self.benefitRatePickerV.delegate = self;
    self.benefitRatePickerV.backgroundColor = [UIColor whiteColor];
    self.benefitRatePickerV.frame = CGRectMake(0, screenH, screenW, 150);
    self.benefitRatePickerV.tag = BenefitRate;
    [self.selectedRateBtn setTitle:self.rateStr forState:UIControlStateNormal];
    [self.selectedRateBtn  addTarget:self action:@selector(popBenefitRatePickerView) forControlEvents:UIControlEventTouchUpInside];
    
    self.benefitRatePikcerToolBar = [[UIToolbar alloc] init];
    self.benefitRatePikcerToolBar.frame = CGRectMake(0, self.benefitRatePickerV.frame.origin.y, screenW, toolViewH);
    UIBarButtonItem *doneBenefitRatePickerButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(inBenefitRatePickerView)];
    self.benefitRatePikcerToolBar.items = @[spacePickerButton,doneBenefitRatePickerButton];
    
    [self.view addSubview:self.benefitRatePickerV];
    [self.view addSubview:self.benefitRatePikcerToolBar];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self resetCondition];
}
#pragma mark - custom method
- (void)resetCondition{
    NSLog(@"重置条件");
    [self constructeRadioGruopWithCondNum:self.itemStatusCond ColNumber:3 ColSpace:1 RowSpace:1 GroupId:ItemStatusGroupId ContainView:self.itemStatusRGV];
    [self constructeRadioGruopWithCondNum:self.itemTypeCond ColNumber:3 ColSpace:1 RowSpace:1 GroupId:GdItemTypeGroupId ContainView:self.itemTypeRGV];
    [self.selectedDaysBtn setTitle:self.interestDaysConditons[0] forState:UIControlStateNormal];
    [self.selectedRateBtn setTitle:self.benefitRateConditons[0] forState:UIControlStateNormal];
    [self configeration];
}
- (void)confirmCondition{
    if ([self.statusCondition count] != 0) {
        [self.rules addObject:self.statusCondition];
    }
    if ([self.typeCondition count] != 0) {
        [self.rules addObject:self.typeCondition];
    }
    if ([self.dayLowCondition count] != 0) {
        [self.rules addObject:self.dayLowCondition];
    }
    if ([self.dayHighCondition count] != 0) {
        [self.rules addObject:self.dayHighCondition];
    }
    if ([self.rateHighCondition count] != 0) {
        [self.rules addObject:self.rateHighCondition];
    }
    if ([self.rateLowCondition count] != 0) {
        [self.rules addObject:self.rateLowCondition];
    }
    NSLog(@"确认条件%@",self.rules);
    self.addRules(self.rules);
    [self dismiss:YES];
}

-(void)addItemStatusCondition:(NSString *)itemStatus
{
    [self.statusCondition removeAllObjects];
    [self.statusCondition setValue:@"itemStatus" forKey:@"field"];
    [self.statusCondition setValue:@"et" forKey:@"op"];
    [self.statusCondition setValue:itemStatus forKey:@"data"];
}
-(void)addGdItemTypeCondition:(NSString *)gdItemType
{
    [self.typeCondition removeAllObjects];
    [self.typeCondition setValue:@"gdItemType" forKey:@"field"];
    [self.typeCondition setValue:@"et" forKey:@"op"];
    [self.typeCondition setValue:gdItemType forKey:@"data"];
}
-(void)addInterestDaysConditionWithDayLow:(NSString *)dayLow DayHigh:(NSString *)dayHigh
{
    if (![dayHigh isEqualToString:@"不限"]) {
        [self.dayHighCondition removeAllObjects];
        [self.dayHighCondition setValue:@"itemDays" forKey:@"field"];
        [self.dayHighCondition setValue:@"let" forKey:@"op"];
        [self.dayHighCondition setValue:dayHigh forKey:@"data"];
    }
    
    [self.dayLowCondition removeAllObjects];
    [self.dayLowCondition setValue:@"itemDays" forKey:@"field"];
    [self.dayLowCondition setValue:@"get" forKey:@"op"];
    [self.dayLowCondition setValue:dayLow forKey:@"data"];
}
-(void)addBenefitRateConditionWihtLowRate:(NSString *)lowRate HeighRate:(NSString *)heighRate
{
    [self.rateLowCondition removeAllObjects];
    [self.rateLowCondition setValue:@"benefitRate" forKey:@"field"];
    [self.rateLowCondition setValue:@"get" forKey:@"op"];
    [self.rateLowCondition setValue:lowRate forKey:@"data"];
    
    [self.rateHighCondition removeAllObjects];
    [self.rateHighCondition setValue:@"benefitRate" forKey:@"field"];
    [self.rateHighCondition setValue:@"let" forKey:@"op"];
    [self.rateHighCondition setValue:heighRate forKey:@"data"];
}
-(void)addCondition:(id)sender
{
    MapRadioButton *radio = (MapRadioButton *)sender;
    if ([radio.groupId isEqualToString:ItemStatusGroupId]) {
        switch (radio.tag) {
            case condPeraper:
                [self addItemStatusCondition:@"8"];
                break;
            case condRaising:
                [self addItemStatusCondition:@"7"];
                break;
            case condSuccesss:
                [self addItemStatusCondition:@"9"];
                break;
            case condReturning:
                [self addItemStatusCondition:@"21"];
                break;
            case condReturnEnd:
                [self addItemStatusCondition:@"20"];
            default:
                break;
        }
    }else if ([radio.groupId isEqualToString:GdItemTypeGroupId]){
        switch (radio.tag) {
            case condZichang:
                [self addGdItemTypeCondition:@"0"];
                break;
            case condDiya:
                [self addGdItemTypeCondition:@"2"];
                break;
            case condSanNong:
                [self addGdItemTypeCondition:@"3"];
                break;
            case condDanBao:
                [self addGdItemTypeCondition:@"1"];
                break;
            case condJinRong:
                [self addGdItemTypeCondition:@"4"];
            default:
                break;
        }
    }
    
}
-(void)addconditionWihtPicker:(UIPickerView *)pickerView row:(NSInteger)row
{
    switch (row) {
        case 1:
            if (pickerView.tag == InterestDays) {
                [self addInterestDaysConditionWithDayLow:@"0" DayHigh:@"90"];
            }else if (pickerView.tag == BenefitRate){
                [self addBenefitRateConditionWihtLowRate:@"7" HeighRate:@"9"];
            }
            break;
        case 2:
            if (pickerView.tag == InterestDays) {
                [self addInterestDaysConditionWithDayLow:@"91" DayHigh:@"180"];
            }else if (pickerView.tag == BenefitRate){
                [self addBenefitRateConditionWihtLowRate:@"9" HeighRate:@"11"];
            }
            break;
        case 3:
            if (pickerView.tag == InterestDays) {
                [self addInterestDaysConditionWithDayLow:@"181" DayHigh:@"270"];
            }else if (pickerView.tag == BenefitRate){
                [self addBenefitRateConditionWihtLowRate:@"11" HeighRate:@"13"];
            }
            break;
        case 4:
            if (pickerView.tag == InterestDays) {
                [self addInterestDaysConditionWithDayLow:@"271" DayHigh:@"360"];
            }else if (pickerView.tag == BenefitRate){
                [self addBenefitRateConditionWihtLowRate:@"13" HeighRate:@"15"];
            }
            break;
        case 5:
            if (pickerView.tag == InterestDays) {
                [self addInterestDaysConditionWithDayLow:@"361" DayHigh:@"不限"];
            }else if (pickerView.tag == BenefitRate){
                [self addBenefitRateConditionWihtLowRate:@"0" HeighRate:@"7"];
            }
            break;
        default:
            break;
    }
}

#pragma mark - configeration
- (void)configeration
{
    self.statusCondition = [NSMutableDictionary dictionary];
    self.typeCondition = [NSMutableDictionary dictionary];
    self.dayHighCondition = [NSMutableDictionary dictionary];
    self.dayLowCondition = [NSMutableDictionary dictionary];
    self.statusCondition = [NSMutableDictionary dictionary];
    self.rateLowCondition = [NSMutableDictionary dictionary];
    self.rateHighCondition = [NSMutableDictionary dictionary];
    self.rules = [NSMutableArray array];
}

- (NSArray *)getInterestDaysCondition
{
    NSArray *array = [[NSArray alloc] initWithObjects:@"不限",@"90天及以下",@"91天－180天",@"181天－270天",@"271天－360天",@"361天及以上",nil];
    return  array;
}
- (NSArray *)getBenefitRateCondition
{
    NSArray *array = [[NSArray alloc] initWithObjects:@"不限",@"7-9%",@"9-11%",@"11-13%",@"13-15%",@"7%以下",nil];
    return  array;
}
- (NSArray *)getConditionStrWithName:(NSInteger)condtion
{
    NSArray *array = [[NSArray alloc] init];
    switch (condtion) {
            case ItemStatus:
        {
            array = [[NSArray alloc] initWithObjects:@"预热中",@"募集中",@"募集成功",@"还款中",@"还款完成",nil];
        }
            break;
            case GdItemTpye:
        {
            array = [[NSArray alloc] initWithObjects:@"政信资产贷",@"物权质押贷",@"普惠三农贷",@"中小企业担保贷",@"消费金融贷", nil];
        }
            break;
        default:
            break;
    }
    return array;
}
- (void)popDaysPickerView
{
    NSLog(@"popDaysPickerView");
    self.interestDaysPickerV.frame = CGRectMake(0, self.daySelectedV.frame.origin.y + toolViewH, screenW, self.daySelectedV.frame.size.height + self.daySelectedV.frame.size.height - toolViewH);
    self.interestDaysPikcerToolBar.frame = CGRectMake(0, self.interestDaysPickerV.frame.origin.y - toolViewH, screenW, toolViewH);
    
}
-(void)inDayasPickerView
{
    NSLog(@"inDayasPickerView");
    self.interestDaysPickerV.frame = CGRectMake(0, screenH, screenW, 150);
    self.interestDaysPikcerToolBar.frame = CGRectMake(0, self.interestDaysPickerV.frame.origin.y, screenW, toolViewH);
    [self.selectedDaysBtn setTitle:self.dayStr forState:UIControlStateNormal];
}
- (void)popBenefitRatePickerView
{
    NSLog(@"popBenefitRatePickerView");
    self.benefitRatePickerV.frame = CGRectMake(0, self.gdAnnualizedBenefitRateV.frame.origin.y + toolViewH, screenW, self.gdAnnualizedBenefitRateV.frame.size.height + self.buttonView.frame.size.height - toolViewH);
    self.benefitRatePikcerToolBar.frame = CGRectMake(0, self.benefitRatePickerV.frame.origin.y - toolViewH, screenW, toolViewH);
    
}
-(void)inBenefitRatePickerView
{
    NSLog(@"inBenefitRatePickerView");
    self.benefitRatePickerV.frame = CGRectMake(0, screenH, screenW, 150);
    self.benefitRatePikcerToolBar.frame = CGRectMake(0, self.benefitRatePickerV.frame.origin.y, screenW, toolViewH);
    [self.selectedRateBtn setTitle:self.rateStr forState:UIControlStateNormal];
}
- (void)constructeRadioGruopWithCondNum:(NSMutableArray*)condition ColNumber:(int)col_number  ColSpace:(int)col_space RowSpace:(int)row_space GroupId:(NSString *)groupId ContainView:(UIView*)containV
{
    int cond_num = (int)[condition count];
    int row_number = (cond_num - 1)/col_number + 1;
    UIView *groupV = [[UIView alloc] init];
    switch (containV.tag) {
        case ItemStatusGroup:
            groupV.frame = CGRectMake(leftDis, self.itemStatus.frame.origin.y + self.itemStatus.frame.size.height + topDis, screenW - 2 * leftDis, containV.frame.size.height - (self.itemStatus.frame.origin.y + self.itemStatus.frame.size.height) - 2 * topDis);
            break;
        case GditemTYpeGRoup:
            groupV.frame = CGRectMake(leftDis, self.gdItemType.frame.origin.y + self.gdItemType.frame.size.height + topDis, screenW - 2 * leftDis, containV.frame.size.height - (self.gdItemType.frame.origin.y + self.gdItemType.frame.size.height) - 2 * topDis);
        default:
            break;
    };
    for (int i = 0,x = 0, y = 12; i < cond_num ; i++) {
        MapRadioButton *radio = [[MapRadioButton alloc] initWithDelegate:self groupId:groupId normalBackgroundImage:@"radio-unselected" selectedBackgroundImage:@"radio-selected"];
        [radio setTitle:condition[i] forState:UIControlStateNormal];
        [radio setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [radio.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
        radio.tag = i;
        [radio addTarget:self action:@selector(addCondition:) forControlEvents:UIControlEventTouchUpInside];
        //布局
        int row = i / col_number;//行号
        int col = i % col_number;//列号
        int radio_width = (groupV.frame.size.width - (col_number-1)*col_space) / col_number;
        int radio_height = (groupV.frame.size.height - (row_number-1)*row_space) / row_number;
        x = col * (radio_width + col_space);
        y = row * (radio_height + row_space);
        
        radio.frame = CGRectMake(x, y, radio_width, radio_height);
        [groupV addSubview:radio];
    }
    [containV addSubview:groupV];
}
#pragma mark - PickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    switch (pickerView.tag) {
        case InterestDays:
            return 1;
            break;
        case BenefitRate:
            return 1;
        default:
            return 1;
            break;
    }
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (pickerView.tag) {
        case InterestDays:
            return [self.interestDaysConditons count];
            break;
        case BenefitRate:
            return [self.benefitRateConditons count];
            break;
        default:
            return 0;
            break;
    }
}
#pragma mark - PickerViewDelegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    NSLog(@"选中第%ld个",row);
    switch (pickerView.tag) {
        case InterestDays:
            self.dayStr = [NSString stringWithFormat:@"%@",self.interestDaysConditons[row]];
            break;
        case BenefitRate:
            self.rateStr = [NSString stringWithFormat:@"%@",self.benefitRateConditons[row]];
            break;
        default:
            break;
    }
    [self addconditionWihtPicker:pickerView row:row];

}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (pickerView.tag) {
        case InterestDays:
            return [self.interestDaysConditons objectAtIndex:row];
            break;
        case BenefitRate:
            return [self.benefitRateConditons objectAtIndex:row];
            break;
        default:
            break;
    }
    return nil;
}

@end
